import {
  LOGIN_START,
  LOGIN_SUCCESS,
  LOGIN_FAILED,
  LOGOUT
} from '../actions/user'

const userLoginInfo = JSON.parse(window.localStorage.getItem('userLoginInfo'))
const userData = Object.assign({ displayName: '' }, userLoginInfo)
const initState = {
  ...userData,
  isLoading: false,
  hasLogin: userLoginInfo ? true : false
}
export default (state = initState, action) => {
  switch (action.type) {
    case LOGIN_START:
      return {
        ...state,
        isLoading: true
      }
    case LOGIN_SUCCESS:
      const newData = {
        ...state,
        ...action.payload.data,
        isLoading: false,
        hasLogin: true
      }
      window.localStorage.setItem(
        'userLoginInfo',
        JSON.stringify(action.payload.data)
      )
      console.log(newData)
      return newData
    case LOGIN_FAILED:
      console.log('登录失败')
      return {
        ...state,
        isLoading: false,
        hasLogin: false
      }
    case LOGOUT:
      window.localStorage.removeItem('userLoginInfo')
      return {
        ...state,
        hasLogin: false
      }
    default:
      return state
  }
}
